package com.chery.media.ui.play.bluetooth

import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import com.chery.media.R
import com.chery.media.contacts.MusicType
import com.chery.media.databinding.FragmentBluetoothBinding
import com.chery.media.library.base.BaseVMFragment
import com.chery.media.library.base.NoViewModel
import com.chery.media.library.extend.clickNoRepeat
import com.chery.media.library.extend.loadPicture
import com.chery.media.library.extend.toTime
import com.chery.media.music.BluetoothMusicTool
import com.chery.media.ui.play.playViewModel

class BlueToothFragment : BaseVMFragment<NoViewModel, FragmentBluetoothBinding>() {

    private var isResume = false

    override val layoutId: Int
        get() = R.layout.fragment_bluetooth

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        BluetoothMusicTool.init()
        val intent = Intent(Settings.ACTION_BLUETOOTH_SETTINGS)
        startActivity(intent)
    }

    override fun onResume() {
        super.onResume()
        isResume = true
        if (playViewModel.currentType.value == MusicType.BLUETOOTH) {
            playViewModel.servicePlayMusic(true)
            playViewModel.bluetoothPlayMusic(false)
        }
    }

    override fun initObserve() {
        // 显示当前的音乐信息、更新当前播放的音乐进度
        playViewModel.currentBluetoothPlayMusic.observe(this) {
            if (it.isPlaying == true) {
                mBinding.pause.setImageResource(R.drawable.svg_play_pause)
            } else {
                mBinding.pause.setImageResource(R.drawable.svg_play)
            }
            mBinding.musicName.text = it.musicName
            mBinding.musicAuthor.text = it.musicAuthor
            val totalTime = (it.totalTime ?: "0").toFloat()
            mBinding.totalTime.text = (it.totalTime ?: "0").toTime()
            mBinding.musicCover.loadPicture(it.musicCover, R.drawable.ic_default_cover)
            if (playViewModel.currentType.value == MusicType.BLUETOOTH) {
                mBinding.musicBluetoothLyrics.text = ""
            } else {
                mBinding.musicBluetoothLyrics.text = ""
            }
            mBinding.playPosition.text = (it.playPosition ?: "0").toTime()
            val seekBarProgress = ((it.playPosition ?: "0").toFloat() / totalTime) * 100
            mBinding.musicSeeKBar.progress = seekBarProgress.toInt()
        }
    }

    override fun initListener() {
        // 上一首
        mBinding.previousSong.clickNoRepeat(interval = 0) {
            playViewModel.playPrevious()
        }
        // 播放暂停
        mBinding.pause.clickNoRepeat(interval = 0) {
            playViewModel.continuePlayOrPause()
        }
        // 下一首
        mBinding.nextSong.clickNoRepeat(interval = 0) {
            playViewModel.playNext()
        }
    }

    companion object {
        fun newInstance() = BlueToothFragment()
    }

}